import { useState, useEffect } from 'react';
import type { StepProps } from './types';
import type { ImportItem } from './types';
import { RiskLevel, ComplianceStatus, getRiskLevelText, getComplianceStatusText } from '@/types/work';
import { showMessage } from '@/components/common/MessageTip';
import { Trash2, Edit2, Check, X } from 'lucide-react';
import { useBusiness } from '@/stores/useBusinessStore';

// 风险等级样式映射（仅样式相关）
const riskLevelStyleMap: Record<RiskLevel, string> = {
  [RiskLevel.VERY_HIGH]: 'bg-red-100 text-red-800',
  [RiskLevel.HIGH]: 'bg-red-100 text-red-800',
  [RiskLevel.MEDIUM]: 'bg-yellow-100 text-yellow-800',
  [RiskLevel.LOW]: 'bg-green-100 text-green-800',
  [RiskLevel.VERY_LOW]: 'bg-blue-100 text-blue-800',
  [RiskLevel.NOT_APPLICABLE]: 'bg-slate-100 text-slate-800'
};

// 合规状态样式映射（仅样式相关）
const complianceStatusStyleMap: Record<ComplianceStatus, string> = {
  [ComplianceStatus.NON_COMPLIANT]: 'bg-red-100 text-red-800',
  [ComplianceStatus.PARTIALLY_COMPLIANT]: 'bg-yellow-100 text-yellow-800',
  [ComplianceStatus.FULLY_COMPLIANT]: 'bg-green-100 text-green-800',
  [ComplianceStatus.NOT_APPLICABLE]: 'bg-slate-100 text-slate-800'
};

interface PreviewStepProps extends StepProps {
  importData: ImportItem[];
}

const PreviewStep = ({ onBack, onClose, onNext, importData }: PreviewStepProps) => {
  const [items, setItems] = useState<ImportItem[]>(importData);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editValue, setEditValue] = useState<string>('');
  
  // 获取评估类型
  const { selectedBusiness } = useBusiness();
  const assessmentType = selectedBusiness?.assessmentType;

  // 分页状态
  const pageSizeOptions = [5, 10, 20] as const;
  const [itemsPerPage, setItemsPerPage] = useState<typeof pageSizeOptions[number]>(10);
  const [currentPage, setCurrentPage] = useState(1);
  const totalPages = Math.max(1, Math.ceil(items.length / itemsPerPage));

  // 当数据变化时确保当前页码有效
  useEffect(() => {
    setCurrentPage(prev => (prev > totalPages ? totalPages : prev));
  }, [totalPages]);

  // 当每页数量变化时重置到第一页
  useEffect(() => {
    setCurrentPage(1);
  }, [itemsPerPage]);

  // 当前页的数据
  const paginatedItems = items.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const handleDelete = (id: string) => {
    setItems(items.filter(item => item.id !== id));
  };

  const handleStartEdit = (id: string, inspector: string) => {
    setEditingId(id);
    setEditValue(inspector || '');
  };

  const handleSaveEdit = (id: string) => {
    setItems(items.map(item => 
      item.id === id ? { ...item, inspector: editValue } : item
    ));
    setEditingId(null);
    setEditValue('');
  };

  const handleCancelEdit = () => {
    setEditingId(null);
    setEditValue('');
  };

  const handleImport = async () => {
    // 如果正在编辑，不允许导入
    if (editingId !== null) {
      showMessage('warning', '请先完成编辑再提交');
      return;
    }

    try {
      await onNext(items);
      showMessage('success', '导入成功');
      onClose();
    } catch (error) {
      showMessage('error', '导入失败');
    }
  };

  // 文本截断函数
  const truncateText = (text: string, maxLength: number) => {
    if (!text) return '';
    return text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
  };

  return (
    <div className="space-y-6">
      <div className="space-y-2">
        <h3 className="text-lg font-medium text-slate-900">预览检查项</h3>
        <p className="text-sm text-slate-500">
          请检查导入的检查项信息，您可以修改检查描述或删除不需要的项目
        </p>
      </div>

      <div className="rounded-md border">
        <div className="relative w-full overflow-x-auto" style={{ maxHeight: 'calc(100vh - 400px)' }}>
          <table className="w-full caption-bottom text-sm sticky top-0">
            <thead className="[&_tr]:border-b sticky top-0 bg-card z-10">
              <tr className="border-b transition-colors hover:bg-slate-50/50">
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500">标题</th>
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500">描述</th>
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500">指引</th>
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500">检查描述</th>
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500">类型</th>
                <th className="h-12 px-4 text-left align-middle font-medium text-slate-500">状态</th>
                <th className="h-12 px-4 text-right align-middle font-medium text-slate-500">操作</th>
              </tr>
            </thead>
            <tbody className="[&_tr:last-child]:border-0">
              {items.length > 0 ? (
                paginatedItems.map((item) => (
                  <tr key={item.id} className="border-b transition-colors hover:bg-slate-50">
                    <td className="p-4 align-middle">
                      <div className="max-w-[200px] truncate" title={item.title}>
                        {truncateText(item.title || '', 30)}
                      </div>
                    </td>
                    <td className="p-4 align-middle">
                      <div className="max-w-[200px] truncate" title={item.description}>
                        {truncateText(item.description || '', 30)}
                      </div>
                    </td>
                    <td className="p-4 align-middle">
                      <div className="max-w-[200px] truncate" title={item.guide}>
                        {truncateText(item.guide || '', 30)}
                      </div>
                    </td>
                    <td className="p-4 align-middle">
                      {editingId === item.id ? (
                        <input
                          type="text"
                          value={editValue}
                          onChange={(e) => setEditValue(e.target.value)}
                          className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                          autoFocus
                        />
                      ) : (
                        <div className="text-sm text-slate-900">
                          {item.inspector || '-'}
                        </div>
                      )}
                    </td>
                    <td className="p-4 align-middle">
                      <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                        item.compliance_type === 'risk' 
                          ? 'bg-red-100 text-red-800' 
                          : 'bg-blue-100 text-blue-800'
                      }`}>
                        {item.compliance_type === 'risk' ? '风险项' : '保障项'}
                      </span>
                    </td>
                    <td className="p-4 align-middle">
                      {item.compliance_type === 'risk' ? (
                        <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                          item.risk_level ? riskLevelStyleMap[item.risk_level] : 'bg-slate-100 text-slate-800'
                        }`}>
                          {item.risk_level ? getRiskLevelText(item.risk_level, assessmentType) : '未设置'}
                        </span>
                      ) : (
                        <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                          item.compliance_status ? complianceStatusStyleMap[item.compliance_status] : 'bg-slate-100 text-slate-800'
                        }`}>
                          {item.compliance_status ? getComplianceStatusText(item.compliance_status, assessmentType) : '未设置'}
                        </span>
                      )}
                    </td>
                    <td className="p-4 align-middle text-right">
                      <div className="flex items-center justify-end gap-2">
                        {editingId === item.id ? (
                          <>
                            <button
                              onClick={() => handleSaveEdit(item.id)}
                              className="inline-flex h-9 w-9 items-center justify-center whitespace-nowrap rounded-md border border-green-200 bg-white text-sm font-medium text-green-600 shadow-sm transition-colors hover:bg-green-50 hover:text-green-700 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-green-500"
                              aria-label="保存"
                            >
                              <Check className="h-4 w-4" />
                            </button>
                            <button
                              onClick={handleCancelEdit}
                              className="inline-flex h-9 w-9 items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white text-sm font-medium text-slate-500 shadow-sm transition-colors hover:bg-slate-50 hover:text-slate-700 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-500"
                              aria-label="取消"
                            >
                              <X className="h-4 w-4" />
                            </button>
                          </>
                        ) : (
                          <>
                            <button
                              onClick={() => handleStartEdit(item.id, item.inspector)}
                              className="inline-flex h-9 w-9 items-center justify-center whitespace-nowrap rounded-md border border-blue-200 bg-white text-sm font-medium text-blue-600 shadow-sm transition-colors hover:bg-blue-50 hover:text-blue-700 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-blue-500"
                              aria-label="修改"
                            >
                              <Edit2 className="h-4 w-4" />
                            </button>
                            <button
                              onClick={() => handleDelete(item.id)}
                              className="inline-flex h-9 w-9 items-center justify-center whitespace-nowrap rounded-md border border-red-200 bg-white text-sm font-medium text-red-500 shadow-sm transition-colors hover:bg-red-50 hover:text-red-700 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500"
                              aria-label="删除"
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="h-24 p-4 text-center text-slate-500">
                    没有可预览的检查项
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* 分页控件 */}
      {items.length > 0 && (
        <div className="flex flex-col items-end gap-2 py-3 sm:flex-row sm:items-center sm:justify-end">
          {/* 每页显示数量选择器 */}
          <div className="flex items-center gap-1 text-sm text-slate-700">
            <span>每页显示</span>
            <select
              value={itemsPerPage}
              onChange={e => setItemsPerPage(Number(e.target.value) as typeof pageSizeOptions[number])}
              className="rounded-md border border-slate-300 bg-white px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
              aria-label="选择每页展示数量"
            >
              {pageSizeOptions.map(size => (
                <option key={size} value={size}>{size}</option>
              ))}
            </select>
          </div>

          <div className="flex items-center space-x-2">
            <button
              onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
              disabled={currentPage === 1}
              className="inline-flex items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium shadow-sm transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 disabled:pointer-events-none disabled:opacity-50"
            >
              上一页
            </button>
            <span className="text-sm text-slate-700">
              {currentPage}/{totalPages}
            </span>
            <button
              onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
              disabled={currentPage === totalPages}
              className="inline-flex items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium shadow-sm transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 disabled:pointer-events-none disabled:opacity-50"
            >
              下一页
            </button>
          </div>
        </div>
      )}

      {/* 操作按钮 */}
      <div className="flex items-center justify-between pt-4">
        <button
          onClick={onBack}
          className="inline-flex items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white px-4 py-2 text-sm font-medium shadow-sm transition-colors hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950"
        >
          上一步
        </button>
        <div className="space-x-3">
          <button
            onClick={onClose}
            className="inline-flex items-center justify-center whitespace-nowrap rounded-md border border-slate-200 bg-white px-4 py-2 text-sm font-medium shadow-sm transition-colors hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950"
          >
            取消
          </button>
          <button
            onClick={handleImport}
            disabled={items.length === 0 || editingId !== null}
            className="inline-flex items-center justify-center whitespace-nowrap rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 disabled:pointer-events-none disabled:opacity-50"
            title={editingId !== null ? '请先完成编辑再提交' : undefined}
          >
            {editingId !== null ? '请先完成编辑' : '确认导入'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default PreviewStep;
